<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 自定义组件，标题 -->
      <PageTitle :show-before="true">
        <template v-slot:before>
          <h2>{{ $t('route.productCate') }}</h2>
        </template>
        <template v-slot:after>
          <el-button class="filter-item" size="medium" style="margin-left: 10px;" type="primary" icon="el-icon-edit" :disabled="!checkPermission('productCate-add')" @click="addOrEidt('add',0)">{{ $t('button.add') }}</el-button>
        </template>
      </PageTitle>
      <!-- 搜索筛选 -->
      <el-row :gutter="20" style="margin-top:20px">
        <el-col :span="4">
          <el-select v-model.number="query.type" :placeholder="$t('table.selectThe')+'类型'">
            <el-option v-for="(item,index) in groupType" :key="index" :label="item.value" :value="item.id" />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" icon="el-icon-search" @click="search">{{ $t('button.search') }}</el-button>
        </el-col>
      </el-row>
      <!-- 数据表 -->
      <el-table
        :data="list"
        row-key="id"
        border
        default-expand-all:false
        max-height="800"
        :tree-props="{children: 'children'}"
        style="margin-top: 20px;"
      >
        <el-table-column prop="id" label="ID" sortable width="100" align="left" />
        <el-table-column prop="name" :label="$t('table.ForeignLanguageName')" />
        <el-table-column prop="type" label="类型">
          <template slot-scope="{row}">
            {{ row.type | shopType }}
          </template>
        </el-table-column>
        <el-table-column prop="pic" :label="$t('table.CatePic')">
          <template slot-scope="{row}">
            <div class="table-img"><img :src="row.pic" width="100%"></div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.state')" prop="status" class-name="status-col" width="100">
          <template slot-scope="{row}">
            <el-tag :type="row.status|statusFilter">
              {{ row.status | shopCate }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" :label="$t('table.sort')" width="250">
          <template slot-scope="{row}">
            <template v-if="row.isedit">
              <el-input v-model="row.sort" class="edit-input" size="small" style="width: 50%;" />
              <el-button
                style="margin-left: 10px;"
                class="cancel-btn"
                size="small"
                icon="el-icon-refresh"
                type="warning"
                @click="confirmEdit(row)"
              >
                {{ $t('button.confirm') }}
              </el-button>
            </template>
            <span v-else>{{ row.sort }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.creationTime')" prop="createtime" sortable width="180">
          <template v-slot="{row}">
            {{ row.createtime| timeStanp }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.actions')" align="center" width="400" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button type="success" size="mini" :disabled="!checkPermission('productCate-add-sub')" @click="addOrEidt('add',row.id)">
              {{ $t('button.AddSub') }}
            </el-button>
            <el-button type="primary" size="mini" :disabled="!checkPermission('productCate-edit')" @click="addOrEidt('edit',row)">
              {{ $t('button.edit') }}
            </el-button>
            <el-button v-if="row.isedit" type="warning" size="mini" @click="cancelEdit(row)">
              {{ $t('button.cancel') }}
            </el-button>
            <el-button v-else type="warning" size="mini" :disabled="!checkPermission('productCate-set')" @click="paixu(row)">
              {{ $t('table.sort') }}
            </el-button>
            <el-button size="mini" type="danger" :disabled="!checkPermission('productCate-del')" @click="delCate(row.id)">
              {{ $t('button.delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加 -->
    <el-dialog :title="dialogTitle" :visible="showDialog" @opened="openDialog" @close="btnCanle">
      <el-form ref="ruleForm" :model="formData" label-width="180px" :rules="rules">
        <el-form-item :label="$t('table.CategoryParent')" prop="pid">
          <el-select v-model="formData.pid" :placeholder="$t('table.selectThe')+' '+$t('table.CategoryParent')">
            <el-option v-for="(item,index) in cateList" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.ForeignLanguageName')" prop="name">
          <el-input v-model="formData.name" style="width:50%" :placeholder="$t('table.enterThe')+' '+$t('table.ForeignLanguageName')" />
        </el-form-item>
        <el-form-item :label="$t('table.ChName')" prop="sub_name">
          <el-input v-model="formData.sub_name" style="width:50%" :placeholder="$t('table.enterThe')+' '+$t('table.ChName')" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model.number="formData.type" :placeholder="$t('table.selectThe')+'类型'">
            <el-option v-for="(item,index) in groupType" :key="index" :label="item.value" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.state')" prop="status">
          <el-select v-model.number="formData.status" :placeholder="$t('table.selectThe')+' '+$t('table.state')">
            <el-option v-for="(item,index) in Is_status" :key="index" :label="item.value" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.CatePic')" prop="pic">
          <ImageUpload ref="staffPhoto" />
        </el-form-item>
        <el-form-item label="banner" prop="banner">
          <ImageUpload ref="bannerPhoto" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="btnCanle">{{ $t('button.cancel') }}</el-button>
        <el-button type="primary" @click="btnOk">{{ $t('button.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import { getShopCateList, sortCate, addShopCate, delShopCate } from '@/api/user'
import user from '@/store/modules/user'
import { tranListTotreeDatCate } from '@/utils'
export default ({
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: [],
      count: null,
      downloadLoading: false,
      dialogTitle: this.$t('button.add'),
      showDialog: false,
      query: {
        bid: 0,
        aid: 1,
        type: undefined,
        page: 1,
        limit: 10
      },
      groupType: [{
        id: 1,
        value: '服务商品'
      },
      {
        id: 2,
        value: '实物商品'
      }],
      cateList: [],
      formData: {
        id: undefined,
        pid: undefined,
        aid: 1,
        name: '',
        sub_name: '',
        status: undefined,
        pic: '',
        banner: '',
        type: undefined
      },
      rules: {
        name: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        pid: [{ required: true, message: '上级不能为空', trigger: 'blur' }]
      },
      Is_status: [{
        id: 0,
        value: this.$t('table.deactivate')
      },
      {
        id: 1,
        value: this.$t('table.normal')
      }]
    }
  },
  created() {
    this.getCate()
    this.query.bid = parseFloat(user.state.userInfo.bid)
  },
  methods: {
    async getCate() { // 请求数据
      this.downloadLoading = true
      const { count, list } = await getShopCateList(this.query)
      this.count = count
      // 给数组对象使用map循环添加新属性
      const lists = list.map((item, index) => {
        return Object.assign(item, { isedit: false })
      })
      // 调用自定义的树状数组函数，处理获取的数组
      this.list = tranListTotreeDatCate(lists, 0)
      const arr = [{ id: 0, name: '一级栏目' }]
      this.cateList = [...arr, ...list]
      this.downloadLoading = false
    },
    changePage(newPage) { // 点击分页
      this.query.page = newPage
      this.getCate()
    },
    addOrEidt(type, row) {
      if (type === 'add') {
        this.dialogTitle = this.$t('button.add')
        const arr = {
          pid: row,
          name: '',
          su_bname: '',
          id: undefined,
          aid: 1,
          status: undefined,
          pic: '',
          banner: '',
          type: undefined
        }
        this.formData = Object.assign({}, arr)
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      } else if (type === 'edit') {
        this.dialogTitle = this.$t('button.edit')
        this.formData = Object.assign({}, row)
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      }
    },
    // 点击确定时 校验整个表单
    async btnOk() {
      try {
        await this.$refs.ruleForm.validate()
        // 调用新增接口
        if (this.formData.parent_id === '0') {
          this.formData.parent_id = 0
        }
        // 读取上传组件的数据
        const fileList = this.$refs.staffPhoto.fileList
        // 循环判断是否已经完成全部上传
        if (fileList.some(item => !item.upload)) {
          //  如果此时去找 upload为false的图片 找到了说明 有图片还没有上传完成
          this.$message.warning(this.$t('prompt.noImage'))
          return
        }
        this.formData = { ...this.formData, pic: fileList && fileList.length ? fileList[0].url : '' }

        // 读取上传组件的数据
        const fileList1 = this.$refs.bannerPhoto.fileList
        // 循环判断是否已经完成全部上传
        if (fileList1.some(item => !item.upload)) {
          //  如果此时去找 upload为false的图片 找到了说明 有图片还没有上传完成
          this.$message.warning(this.$t('prompt.noImage'))
          return
        }
        this.formData = { ...this.formData, banner: fileList1 && fileList1.length ? fileList1[0].url : '' }
        await addShopCate(this.formData)
        // 告诉父组件更新数据
        this.getCate()
        this.showDialog = false
        this.$message.success(this.$t('prompt.success'))
      } catch (error) {
        console.log(error)
      }
    },
    // 删除
    async delCate(row) {
      const data = {
        id: row
      }
      try {
        await this.$confirm(this.$t('prompt.deleteit'))
        await delShopCate(data)
        this.getCate()
        this.$message.success(this.$t('prompt.deletesuccess'))
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 取消重置原来的数据
    btnCanle() {
      this.formData = {
        pid: undefined,
        name: '',
        su_bname: '',
        id: undefined,
        aid: 1,
        status: undefined,
        pic: '',
        banner: '',
        type: undefined
      }
      this.$refs.staffPhoto.fileList = []
      this.$refs.bannerPhoto.fileList = []
      this.$refs.ruleForm.resetFields()// 重置校验结果
      this.showDialog = false
    },
    // 点击排序
    paixu(row) {
      row.isedit = true
    },
    // 取消排序
    cancelEdit(row) {
      row.isedit = false
    },
    // 确认排序
    async confirmEdit(row) {
      const data = {
        id: row.id,
        sort: parseInt(row.sort)
      }
      row.isedit = false
      try {
        await sortCate(data)
        this.$message.success(this.$t('prompt.paixuSuccess'))
        this.getCate()
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 搜索
    search() {
      this.query.page = 1
      this.getCate()
    },
    openDialog() {
      // 判断有icon的数据
      if (this.formData.pic) {
        // 这里我们赋值，同时需要给赋值的地址一个标记 upload: true
        this.$refs.staffPhoto.fileList = [{ url: this.formData.pic, upload: true }]
      }
      // 判断有icon的数据
      if (this.formData.banner) {
        // 这里我们赋值，同时需要给赋值的地址一个标记 upload: true
        this.$refs.bannerPhoto.fileList = [{ url: this.formData.banner, upload: true }]
      }
    }
  }
})
</script>
<style lang="scss">
  .table-img{
    width: 100px;
  }
</style>
